package com.ebt.m.customer.ui;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.EditText;
import android.widget.Toast;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.ebt.m.AppInitService;
import com.ebt.m.R;
import com.ebt.m.activity.BaseToolBarActivity;
import com.ebt.m.commons.buscomponent.permission.RxPermissions;
import com.ebt.m.commons.utils.NetUtils;
import com.ebt.m.commons.utils.RxUtil;
import com.ebt.m.customer.constant.CustomerConstant;
import com.ebt.m.customer.entity.CustomerAtta;
import com.ebt.m.customer.entity.CustomerDetail;
import com.ebt.m.customer.event.EventCustomerAllPageIndex;
import com.ebt.m.customer.event.EventCustomerFloatingButtonAction;
import com.ebt.m.customer.event.EventCustomerListRefresh;
import com.ebt.m.customer.event.EventFloatingActionButton;
import com.ebt.m.customer.event.EventRefreshAttachment;
import com.ebt.m.customer.fakeDialog.util.FakeDialogUtil;
import com.ebt.m.customer.fakeDialog.view.FakeDialogView;
import com.ebt.m.customer.fakeDialog.view.FakeDialogView.ChildModel;
import com.ebt.m.customer.model.CustomerModelNew;
import com.ebt.m.customer.net.http.OSSUploader;
import com.ebt.m.customer.net.json.CustomerCRUDRetJson;
import com.ebt.m.customer.net.json.CustomerDetailJson;
import com.ebt.m.customer.util.CustomerConvertUtil;
import com.ebt.m.customer.util.CustomerNavigator;
import com.ebt.m.customer.util.CustomerRecorder;
import com.ebt.m.customer.util.ToastUtil;
import com.ebt.m.customer.view.CustomerAllContentView;
import com.ebt.m.customer.view.CustomerAllHeaderView;
import com.ebt.m.customer.view.Dialog4CustomerAttachmentRename;
import com.ebt.m.customer.view.RecorderWrapper;
import com.ebt.m.data.CustomerData;
import com.ebt.m.data.bean.EbtFile;
import com.ebt.m.data.entity.Customer;
import com.ebt.m.data.entity.EntityCustomerAttachment;
import com.ebt.m.data.entity.EntityCustomerNote;
import com.ebt.m.data.rxModel.api.EBTAPI;
import com.ebt.m.fileExplore.ui.ActivityFileExplore;
import com.ebt.m.proposal_v2.utils.ProposalUtils;
import com.ebt.m.proposal_v2.widget.dialog.EBTProgressDialog;
import com.ebt.m.utils.DataValidation;
import com.ebt.m.utils.ImageResizer;
import com.ebt.m.utils.ImageSelectUtil;
import com.ebt.m.utils.TalkingDataUtil;
import com.ebt.m.utils.UIHelper;
import com.ebt.m.utils.fileutils.FileUtils;
import com.ebt.m.widget.MDEBTDialog;
import com.ebt.m.widget.image_chooser.ImageChooserActivity;
import com.jakewharton.rxbinding2.view.RxView;
import com.tendcloud.tenddata.TCAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * 客户详情界面
 *
 * @author Rick.Wang
 */
public class ActivityCustomerAll extends BaseToolBarActivity {

    private static final String CAMERA_TARGET = "CameraTarget";

    //views
    private CustomerAllHeaderView mHeaderView;
    private CustomerAllContentView mContentView;
    private FloatingActionButton mFloatingActionButton;
    private MDEBTDialog mMenuDialog;

    //values
    private Intent mGetIntent;
    private String mCustomerUuid;
    private String mCustomerMode = CustomerConstant.CUSTOMER_DETAIL_MODE_ADD;
    private ArrayList<ChildModel> fakeDialogChildrenModels = new ArrayList<>();
    private int mViewPagerIndex = CustomerConstant.CustomerAll.VIEW_PAGER_INDEX_INTERACTION;

    private Bundle mBundle;
    private HashMap<String, Boolean> uploadStateMap = new HashMap<>();
    private CustomerDetail mCustomerDetail;

    private EBTAPI ebtapi = null;

    private Handler uploadHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            switch (message.what) {
                case 100:
                    String path = (String) message.obj;
                    ToastUtil.showToast(path + "附件不存在，请重新选择附件");
                    break;
                case 110:
                    path = (String) message.obj;
                    ToastUtil.showToast(path + " 文件过大，请重新选择文件");
                    break;
                case 120:
                    //网络不通
                    ToastUtil.showToast(getString(R.string.network_fail));
                    break;
                case 130:
                    path = (String) message.obj;
//                    ToastUtil.showToast("文件 " + path + " 上传失败");
                    uploadStateMap.put(path, false);
                    int successNum = getStatusNum(true);
                    int failNum = getStatusNum(false);
                    if ((successNum + failNum) == uploadStateMap.size()) {
                        dismissMaterialishProgressDialog();
                        EventBus.getDefault().post(new EntityCustomerNote());
                        EventBus.getDefault().post(new EventCustomerAllPageIndex(4));
                        EventBus.getDefault().post(new EventRefreshAttachment(false));
                    }
                    break;
                case 140:
                    path = (String) message.obj;
                    uploadStateMap.put(path, true);
                    successNum = getStatusNum(true);
                    failNum = getStatusNum(false);
                    if ((successNum + failNum) == uploadStateMap.size()) {
                        dismissMaterialishProgressDialog();
                        ToastUtil.showToast("附件上传成功");
                        EventBus.getDefault().post(new EntityCustomerNote());
                        EventBus.getDefault().post(new EventCustomerAllPageIndex(4));
                        EventBus.getDefault().post(new EventRefreshAttachment(false));
                    }
                    break;
                case 150:
                    break;
            }
            return false;
        }
    });

    /**
     * 获取上传成功或者失败的状态总数
     *
     * @param isSuccess
     * @return
     */
    private int getStatusNum(boolean isSuccess) {
        int num = 0;
        for (String key : uploadStateMap.keySet()) {
            if (uploadStateMap.get(key) != null && isSuccess == uploadStateMap.get(key)) {
                num += 1;
            }
        }
        return num;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        OSSUploader.init(getApplicationContext());
        initArgs();
        EventBus.getDefault().register(this);
    }


    @Override
    public void init() {
        setContentView(R.layout.activity_customer_all);
        getSupportActionBar().hide();
        initFunctionButtons();
        initActionButton();
        initOthersView();

        mGetIntent = getIntent();
        if (mGetIntent != null) {
            mCustomerUuid = mGetIntent.getStringExtra(CustomerConstant.CUSTOMER_UUID);
            mViewPagerIndex = mGetIntent.getIntExtra(CustomerConstant.CustomerAll.VIEW_PAGER_INDEX,
                    CustomerConstant.CustomerAll.VIEW_PAGER_INDEX_INTERACTION);
        }
        if (TextUtils.isEmpty(mCustomerUuid)) {
            showToast("客户未保存");
            delayFinish();
        } else {
            ebtapi.getCustomerDetail(mCustomerUuid).compose(RxUtil.rxTransformer(this)).subscribe(getCustomerDetailSubscriber());
        }
        updateOtherViews(mCustomerDetail);
    }

    private void initOthersView() {
        mHeaderView = (CustomerAllHeaderView) findViewById(R.id.header_view);
        mContentView = (CustomerAllContentView) findViewById(R.id.content_view);
    }

    private String mAvatarUrl;
    private int mSex;
    private CustomerModelNew customerModelNew;

    private void initArgs() {
        Intent intent = getIntent();
        mSex = intent.getIntExtra(CustomerConstant.SpreadAnim.SEX, 0);
        mAvatarUrl = intent.getStringExtra(CustomerConstant.SpreadAnim.URL_AVATAR);
        mBundle = intent.getExtras();
        customerModelNew = (CustomerModelNew) intent.getSerializableExtra(CustomerConstant.CUSTOMER_DATA);
        //
        if (customerModelNew != null) {
            CustomerDetail customerDetail = new CustomerDetail();
            customerDetail.setName(customerModelNew.name);
            customerDetail.setPortraitPath(customerModelNew.avatarUrl);
            customerDetail.setSex(customerModelNew.sex);
            customerDetail.setTag(customerModelNew.tag);
            customerDetail.setCustomerId(customerModelNew.getCustomerUuid());
            mCustomerDetail = customerDetail;
            if (this.mCustomerUuid == null) {
                this.mCustomerUuid = customerModelNew.getCustomerUuid();
            }
        }
        ebtapi = AppInitService.getEbtApi();
    }

    private void initFunctionButtons() {
        RxView.clicks(findViewById(R.id.btn_delete))
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(aVoid -> {
                    deleteCustomer();
                });
        RxView.clicks(findViewById(R.id.btn_edit))
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(aVoid -> {
                    editCustomer();
                });
        RxView.clicks(findViewById(R.id.btn_cancel))
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(aVoid -> {
                    onBackPressed();
                });
    }

    private void initActionButton() {
        mFloatingActionButton = (FloatingActionButton) findViewById(R.id.floating_action_button);
        fakeDialogChildrenModels.add(new ChildModel(getString(R.string.customer_fab_attachment), R.drawable.ic_action_atta));
        fakeDialogChildrenModels.add(new ChildModel(getString(R.string.customer_fab_note), R.drawable.ic_action_note));
        fakeDialogChildrenModels.add(new ChildModel(getString(R.string.customer_fab_proposal), R.drawable.ic_action_prop));
        fakeDialogChildrenModels.add(new ChildModel(getString(R.string.customer_fab_insurance), R.drawable.ic_action_insu));
        RxView.clicks(mFloatingActionButton)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(aVoid -> {
                    FakeDialogUtil.toggleFakeDialog(this, mFloatingActionButton, fakeDialogChildrenModels, null, false,
                            new FakeDialogView.OnFakeDialogClickListener() {
                                @Override
                                public void onFakeDialogBackgroundClick() {
                                }

                                @Override
                                public void onFakeDialogChildrenClick(int index) {

                                    TalkingDataUtil.onEventWithLabel(TalkingDataUtil.TYPE_CUSTOMER_FAB_CLICK, fakeDialogChildrenModels.get(index - 1).text);
                                    switch (index) {
                                        case 1://附件
                                            pressAttachment();
                                            break;
                                        case 2://笔记
                                            pressNote();
                                            break;
                                        case 3://计划书
                                            pressProposal();
                                            break;
                                        case 4://保单
                                            pressInsurance();
                                            break;
                                    }
                                }
                            });
                });
    }


    private Observer<CustomerDetailJson> getCustomerDetailSubscriber() {
        return new Observer<CustomerDetailJson>() {

            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onComplete() {
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
            }

            @Override
            public void onNext(CustomerDetailJson customerDetailJson) {
                if (customerDetailJson == null) {
                    showToast("客户不存在");
                    delayFinish();
                    return;
                }
                if (customerDetailJson.error != null) {
                    delayFinish();
                    return;
                }
                if (customerDetailJson.error == null) {
                    if (customerDetailJson.data == null) {
                        delayFinish();
                        return;
                    } else {
                        updateOtherViews(customerDetailJson.data);
                    }
                }
            }
        };
    }

    private void showToast(String message) {
        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
    }

    private void updateOtherViews(CustomerDetail customerDetail) {
        mCustomerDetail = customerDetail;
        if (mCustomerDetail != null) {
            mHeaderView.update(mCustomerDetail);
            mContentView.update(mCustomerDetail, mCustomerMode, mCustomerUuid, mViewPagerIndex);
            RxView.clicks(mHeaderView.getAvatarView())
                    .throttleFirst(500, TimeUnit.MILLISECONDS)
                    .subscribe(aVoid -> {
                        editCustomer();
                    });
            RxView.clicks(mHeaderView.getTextViewName())
                    .throttleFirst(500, TimeUnit.MILLISECONDS)
                    .subscribe(aVoid -> {
                        editCustomer();
                    });
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        overridePendingTransition(R.anim.slide_left_in, R.anim.slide_right_out);
    }


    private void pressNote() {
        if (!NetUtils.isNetworkAvailable(this)) {
            ToastUtil.showToast(this.getString(R.string.network_fail));
            return;
        }
        Intent intent = new Intent(this, ActivityCustomerNote.class);
        intent.putExtra(CustomerConstant.CUSTOMER_UUID, mCustomerUuid);
        intent.putExtra(CustomerConstant.CustomerNote.MODE, CustomerConstant.CustomerNote.MODE_ADD);
        startActivity(intent);
        overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
    }

    private void pressProposal() {
        CustomerDetail customer = mContentView.getCustomerDetail();
        Map<String, String> map = new HashMap<String, String>();
        map.put(CustomerConstant.CUSTOMER_UUID, mCustomerUuid);
        ProposalUtils.makeProposalWithCustomer(this, mCustomerUuid);
    }

    private void pressInsurance() {
        Intent createIntent = new Intent(this, PolicyEditActivity.class);
        Bundle data = new Bundle();
        data.putInt(PolicyEditActivity.ARG_FLAG, 0);
        data.putString(PolicyEditActivity.ARG_CUSTOMER_ID, mCustomerUuid);
        createIntent.putExtras(data);
        startActivity(createIntent);
        overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
    }

    private void pressAttachment() {
        if (mMenuDialog == null) {
            String[] menu_messages = new String[]{"拍照", "图库", "其他"};
            mMenuDialog = new MDEBTDialog.Builder(this)
                    .setMessages(menu_messages)
                    .setOnItemClickListener(new MDEBTDialog.OnItemClickListener() {
                        @Override
                        public void onItemClicked(int index) {
                            switch (index) {
                                case 0:
                                    onCamera();
                                    break;
                                case 1:
                                    onImageAlbum();
                                    break;
                                case 2:
                                    Intent fileIntent = new Intent();
                                    fileIntent.setClass(ActivityCustomerAll.this, ActivityFileExplore.class);
                                    startActivityForResult(fileIntent, REQUEST_CODE_PICK_FILE);
                                    break;
                            }
                            TCAgent.onEvent(getApplicationContext(), "add_attachment");
                        }
                    }).setShowTitle(false)
                    .setShowButtons(false).create();
        }
        mMenuDialog.show();
    }

    private static final int REQUEST_CODE_PICK_FILE = 1;
    private static final int REQUEST_CODE_CAMERA = 2;
    private static final int REQUEST_CODE_CAPTURE = 3;
    private String mCameraTarget;
    private File targetFile;
    private RxPermissions rxPermissions;

    public void onCamera() {
        if (rxPermissions == null) {
            rxPermissions = new RxPermissions(this);
        }
        rxPermissions.request(Manifest.permission.CAMERA)
                .subscribe(permission -> {
                    if (permission) {
                        String dir = ImageSelectUtil.getImageCacheDir();
                        if (dir != null && !"".equals(dir)) {
                            String fileName = ImageSelectUtil.getFileName(0, null);
                            mCameraTarget = dir + "/" + fileName;
                            targetFile = ImageSelectUtil.getFile(dir, fileName);
                            ImageSelectUtil.openCamera(this, targetFile, REQUEST_CODE_CAMERA);
                        } else {
                            Toast.makeText(getApplicationContext(), "SD卡不存在", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        UIHelper.makeToast(this, "请在设置中为" + getResources().getString(R.string.app_name) + "开启相机权限");
                    }
                });
    }

    public void onImageAlbum() {
//        ImageSelectUtil.openAlbum(this, REQUEST_CODE_CAPTURE);
        Intent intent = new Intent(this, ImageChooserActivity.class);
        Bundle bundle = new Bundle();
//        bundle.putInt("choosenCount", 1);
        bundle.putInt("maxCount", 9);
        intent.putExtras(bundle);
        startActivityForResult(intent, REQUEST_CODE_CAPTURE);
    }

    private static final int MAX_PATH_LENGTH = 200;

    /**
     * 上传多个文件
     *
     * @param fileListStr
     */
    private void handlePickedPics(ArrayList<String> fileListStr) {
        ArrayList<File> fileList = new ArrayList<>();
        for (int i = 0; i < fileListStr.size(); i++) {
            fileList.add(new File(fileListStr.get(i)));
        }
        EntityCustomerAttachment mContent;
        EntityCustomerAttachment[] entityCustomerAttachments = new EntityCustomerAttachment[fileList.size()];
        File file = null;
        for (int i = 0; i < fileList.size(); i++) {
            file = fileList.get(i);
            EbtFile mEbtFile = FileUtils.convertFileToEbtFile(file);
            if (mEbtFile != null && mEbtFile.path != null) {
                mContent = new EntityCustomerAttachment();
                mContent.setPath(mEbtFile.path);
                mContent.setContent(mEbtFile.size + "");
                mContent.setFileName(file.getName());
                mContent.setFileType(String.valueOf(mEbtFile.type.getValue()));//TODO
                mContent.setRemark(file.getName());
                if (!TextUtils.isEmpty(mEbtFile.packageName)) {
                    mContent.setContent(mEbtFile.packageName + "@" + mEbtFile.activityName);
                }
                entityCustomerAttachments[i] = mContent;
            }
        }
        if (entityCustomerAttachments.length > 0) {
            saveAttachments(entityCustomerAttachments);
        }
    }

    private void handlePickedAttachment(Context context, File file) {
        if (DataValidation.isEmpty(file.getName())) {
            return;
        }
        String suffix = FileUtils.getSuffixFromUrl(file.getName());
        Dialog4CustomerAttachmentRename dialog = Dialog4CustomerAttachmentRename.netInstance(file.getName());
        dialog.setNegativeButton("取消", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismissAllowingStateLoss();
            }
        });
        dialog.setPositiveButton("确定", v -> {
            EbtFile mEbtFile = FileUtils.convertFileToEbtFile(file);
            View view = dialog.getmContentView();
            if (view == null) {
                return;
            }
            EditText mETFileName = (EditText) view.findViewById(R.id.customer_add_attachment_dialog_file_name_et);
            EditText mETFileRemark = (EditText) view.findViewById(R.id.customer_add_attachment_dialog_file_remark_et);
            EntityCustomerAttachment mContent;
            if (mEbtFile != null && !TextUtils.isEmpty(mETFileName.getText().toString().trim())) {
                if (mEbtFile.path != null && mEbtFile.path.length() < MAX_PATH_LENGTH) {
                    mContent = new EntityCustomerAttachment();
                    mContent.setPath(mEbtFile.path);
                    mContent.setContent(mEbtFile.size + "");
                    mContent.setFileName(mETFileName.getText().toString().trim() + suffix);
                    mContent.setFileType(String.valueOf(mEbtFile.type.getValue()));//TODO
                    mContent.setRemark(mETFileRemark.getText().toString().trim());
                    if (!TextUtils.isEmpty(mEbtFile.packageName)) {
                        mContent.setContent(mEbtFile.packageName + "@" + mEbtFile.activityName);
                    }
                    saveAttachment(mContent);
                    dialog.dismissAllowingStateLoss();
                } else {
                    Toast.makeText(context, "文件路径为空，存储失败", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(context, "请输入文件名称", Toast.LENGTH_SHORT).show();
            }
        });
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.add(dialog, "change_file_name");
        ft.commitAllowingStateLoss();
    }

    /**
     * 保存多个文件
     *
     * @param contents
     */
    private void saveAttachments(EntityCustomerAttachment[] contents) {
        //网络不通
        if (!NetUtils.isNetworkAvailable(getApplicationContext())) {
            Message message = uploadHandler.obtainMessage();
            message.what = 120;
            uploadHandler.sendMessage(message);
            return;
        }
        for (EntityCustomerAttachment content : contents) {
            CustomerAtta atta = CustomerConvertUtil.convertAttaEntityToJson(content);
            if (TextUtils.isEmpty(atta.getCustomerId())) {
                atta.setCustomerId(mCustomerUuid);
            }
            String localPath = atta.getPath();
            String attaPath = CustomerConstant.Attachment.DIR_PATH
                    + File.separator
                    + (System.currentTimeMillis() + CustomerConstant.Attachment.ATTA_NAME_SEPARATOR)
                    + atta.getFileName();
            //判断文件是否存在
            if (TextUtils.isEmpty(localPath) || !new File(localPath).exists()) {
                Message message = uploadHandler.obtainMessage();
                message.what = 100;
                message.obj = localPath;
                uploadHandler.sendMessage(message);
                return;
            }
            File f = new File(localPath);
            //判断单个文件是否过大
            if (f.length() > CustomerConstant.Attachment.SIZE_10_M) {
                //文件过大，提示不上传
                Message message = uploadHandler.obtainMessage();
                message.what = 110;
                message.obj = localPath;
                uploadHandler.sendMessage(message);
                return;
            }
        }
        long size = 0;
        //移动网络下，提示是否在移动网络下上传
        NetUtils.NetType netType = NetUtils.getAPNType(getApplicationContext());
        if (netType != NetUtils.NetType.NONE && netType != NetUtils.NetType.WIFI) {
            for (EntityCustomerAttachment content : contents) {
                CustomerAtta atta = CustomerConvertUtil.convertAttaEntityToJson(content);
                String localPath = atta.getPath();
                File f = new File(localPath);
                long singleSize = f.length();
                size += singleSize;
            }
            String fileSize = String.valueOf(size / (1024 * 1024)) + "M";
            String[] messages = new String[]{"选中的文件大小为" + fileSize + ", 确定在移动网络下上传？"};
            new MDEBTDialog.Builder(ActivityCustomerAll.this)
                    .setMessages(messages)
                    .setTitle("文件上传提醒")
                    .setNegativeButton(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            return;
                        }
                    })
                    .setPositiveButton(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            toUpload(contents);

                        }
                    })
                    .setContentViewClickable(false)
                    .create()
                    .show();
        } else {
            toUpload(contents);
        }

    }

    private void toUpload(EntityCustomerAttachment[] contents) {
        showMaterialishProgressDialog();
        uploadStateMap.clear();
        for (EntityCustomerAttachment content : contents) {
            CustomerAtta atta = CustomerConvertUtil.convertAttaEntityToJson(content);
            if (TextUtils.isEmpty(atta.getCustomerId())) {
                atta.setCustomerId(mCustomerUuid);
            }
            String localPath = atta.getPath();
            String attaPath = CustomerConstant.Attachment.DIR_PATH
                    + File.separator
                    + (System.currentTimeMillis() + CustomerConstant.Attachment.ATTA_NAME_SEPARATOR)
                    + atta.getFileName();
            uploadToAli(localPath, attaPath, atta);
        }
    }

    private void saveAttachment(EntityCustomerAttachment content) {
        CustomerAtta atta = CustomerConvertUtil.convertAttaEntityToJson(content);
        if (TextUtils.isEmpty(atta.getCustomerId())) {
            atta.setCustomerId(mCustomerUuid);
        }

        String localPath = atta.getPath();
        String attaPath = CustomerConstant.Attachment.DIR_PATH
                + File.separator
                + (System.currentTimeMillis() + CustomerConstant.Attachment.ATTA_NAME_SEPARATOR)
                + atta.getFileName();
        if (TextUtils.isEmpty(localPath) || !new File(localPath).exists()) {
            Message message = uploadHandler.obtainMessage();
            message.what = 100;
            message.obj = localPath;
            uploadHandler.sendMessage(message);
            return;
        }
        File f = new File(localPath);
        //判断文件是否过大
        if (f.length() > CustomerConstant.Attachment.SIZE_10_M) {
            //文件过大，提示不上传
            ToastUtil.showToast("文件过大，请重新选择文件");
            return;
        }
        //确定是否只在wifi下上传
        if (f.length() > CustomerConstant.Attachment.SIZE_1_M) {
            if (!NetUtils.isNetworkAvailable(getApplicationContext())) {
                ToastUtil.showToast(getString(R.string.network_fail));
            } else {
                //移动网络下，提示是否在移动网络下上传
                if (!NetUtils.isWifiConnected(getApplicationContext())) {
                    String fileSize = String.valueOf(f.length() / (1024 * 1024)) + "M";
                    String[] messages = new String[]{"选中的文件大小为" + fileSize + ", 确定在移动网络下上传？"};
                    new MDEBTDialog.Builder(ActivityCustomerAll.this)
                            .setMessages(messages)
                            .setTitle("文件上传提醒")
                            .setNegativeButton(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    return;
                                }
                            })
                            .setPositiveButton(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    uploadStateMap.clear();
                                    showMaterialishProgressDialog();
                                    uploadToAli(localPath, attaPath, atta);
                                }
                            })
                            .setContentViewClickable(false)
                            .create()
                            .show();
                } else {
                    //wifi下，直接上传
                    uploadStateMap.clear();
                    showMaterialishProgressDialog();
                    uploadToAli(localPath, attaPath, atta);
                }
            }
        } else {
            //小于1M，不判断网络，直接上传
            uploadStateMap.clear();
            showMaterialishProgressDialog();
            uploadToAli(localPath, attaPath, atta);
        }
    }

    private void uploadToAli(String localPath, String attaPath, CustomerAtta atta) {
        uploadStateMap.put(atta.getPath(), null);
        if (FileUtils.nioTransferCopy(new File(localPath), new File(attaPath))) {
            OSSUploader.uploadAttachment(attaPath, new OnOSSUploadResponseListener(atta));
        } else {
            FileUtils.deleteFile(new File(attaPath));
        }
    }

    //显示等待对话框
    private EBTProgressDialog materialishProgressDialog;

    private void showMaterialishProgressDialog() {
        if (materialishProgressDialog == null) {
            materialishProgressDialog = new EBTProgressDialog(this);
            materialishProgressDialog.setCancelable(false);
            materialishProgressDialog.setCanceledOnTouchOutside(false);
        }
        materialishProgressDialog.show();
    }

    private void dismissMaterialishProgressDialog() {
        if (materialishProgressDialog != null) {
            materialishProgressDialog.dismiss();
        }
    }

    /**
     * 上传附件到阿里云服务器监听
     */
    private class OnOSSUploadResponseListener implements OSSCompletedCallback<PutObjectRequest, PutObjectResult> {

        private CustomerAtta atta;
        private String localPath;

        public OnOSSUploadResponseListener(CustomerAtta atta) {
            this.atta = atta;
            this.localPath = atta.getPath();
        }

        @Override
        public void onSuccess(PutObjectRequest putObjectRequest, PutObjectResult putObjectResult) {
            if (putObjectRequest != null) {
                String url = OSSUploader.getPublicUrl(putObjectRequest.getBucketName(), putObjectRequest.getObjectKey());
                atta.setPath(url);
                //上传成功调用接口
                ebtapi.createAtta(atta).compose(RxUtil.rxTransformer(ActivityCustomerAll.this)).subscribe(getAttaCURSubscriber(localPath));
            }
        }

        @Override
        public void onFailure(PutObjectRequest putObjectRequest, ClientException e, ServiceException e1) {
            dismissMaterialishProgressDialog();
            Message message = uploadHandler.obtainMessage();
            message.what = 130;
            message.obj = localPath;
            uploadHandler.sendMessage(message);
            // 请求异常
            if (e != null) {
                // 本地异常如网络异常等
                e.printStackTrace();
            }
            if (e1 != null) {
                // 服务异常
                Log.e("ErrorCode", e1.getErrorCode());
                Log.e("RequestId", e1.getRequestId());
                Log.e("HostId", e1.getHostId());
                Log.e("RawMessage", e1.getRawMessage());
            }
        }
    }


    private Observer<CustomerCRUDRetJson> getAttaCURSubscriber(String path) {

        return new Observer<CustomerCRUDRetJson>() {

            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onComplete() {

            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                Message message = uploadHandler.obtainMessage();
                message.what = 130;
                message.obj = path;
                uploadHandler.sendMessage(message);
            }

            @Override
            public void onNext(CustomerCRUDRetJson customerCreateRetJson) {
                if (customerCreateRetJson == null || customerCreateRetJson.error != null || customerCreateRetJson.data == null) {
                    Message message = uploadHandler.obtainMessage();
                    message.what = 130;
                    message.obj = path;
                    uploadHandler.sendMessage(message);
                    return;
                }
                Message message = uploadHandler.obtainMessage();
                message.what = 140;
                message.obj = path;
                uploadHandler.sendMessage(message);
            }
        };
    }

    private void saveCameraTargetFilePath(Bundle outState) {
        if (!TextUtils.isEmpty(mCameraTarget)) {
            outState.putString(CAMERA_TARGET, mCameraTarget);
        }
    }

    private void restoreCameraTargetFilePath(Bundle savedInstanceState) {
        String x = savedInstanceState.getString(CAMERA_TARGET);
        if (!TextUtils.isEmpty(x)) {
            mCameraTarget = x;
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        saveCameraTargetFilePath(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        restoreCameraTargetFilePath(savedInstanceState);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case REQUEST_CODE_PICK_FILE:
                Bundle b = data.getExtras();
                File returnFile = (File) b.getSerializable(ActivityFileExplore.RETURN_FILE);
                handlePickedAttachment(this, returnFile);
                break;
            case REQUEST_CODE_CAMERA:
                File cameraFile = new File(mCameraTarget);//
                if (cameraFile != null && cameraFile.exists()) {
                    Bitmap bmp = ImageResizer.decodeBitmapFromFile(mCameraTarget, 480, 800);
                    if (bmp != null) {
                        // 如果拍照图片偏转，则拨正并重新保存
                        int angle = ImageSelectUtil.getPhotoDegree(mCameraTarget);
                        if (angle > 0) {
                            bmp = ImageSelectUtil.rotateImage(angle, bmp);
                            ImageSelectUtil.saveBitmap(bmp, mCameraTarget);
                        }
                    }
                    handlePickedAttachment(this, cameraFile);
                }
                break;
            case REQUEST_CODE_CAPTURE:
                if (data != null) {
//                    String path = ImageSelectUtil.getPathFromUri(this, data.getItemData());
//                    if (null != path && !"".equals(path)) {
//                        File albumFile = new File(path);
//                        if (null != albumFile && albumFile.exists()) {
//                            handlePickedAttachment(this, albumFile);
//                        }
//                    }
                    ArrayList<String> list = (ArrayList<String>) data.getSerializableExtra(ImageChooserActivity.requestCodeKey);
                    handlePickedPics(list);
                }
                break;
            default:
                break;
        }
    }

    private void editCustomer() {
        if (!TextUtils.isEmpty(mCustomerUuid)) {
            CustomerNavigator.startActivityCustomerDetailInEdit(this, mCustomerUuid);
            overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
        }
    }

    private void deleteCustomer() {
        if (!TextUtils.isEmpty(mCustomerUuid)) {
            String[] messages = new String[]{"确定删除此客户？"};
            new MDEBTDialog.Builder(ActivityCustomerAll.this)
                    .setMessages(messages)
                    .setTitle("删除客户")
                    .setNegativeButton(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                        }
                    })
                    .setPositiveButton(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Thread deleteCustomer = new Thread() {
                                @Override
                                public void run() {
                                    if (TextUtils.isEmpty(mCustomerUuid)) {
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                onBackPressed();
                                            }
                                        });
                                    } else {
                                        CustomerData cd = new CustomerData(getApplicationContext());
                                        Customer customer = cd.getCustomerByUUID(mCustomerUuid);
                                        boolean isImported = (customer != null && customer.getState() != null && customer.getState() == 1);
                                        cd.pretendDeleteACustomerByUuid(mCustomerUuid);
                                        cd.pretendDeleteByColumeNameAndValue(CustomerConstant.TABLE_CUSTOMER_CONTACT,
                                                CustomerConstant.CUSTOMER_UUID, mCustomerUuid);
                                        cd.pretendDeleteByColumeNameAndValue(CustomerConstant.CustomerFromContact.TABLE_NAME,
                                                CustomerConstant.CUSTOMER_UUID, mCustomerUuid);
                                        CustomerRecorder.deleteCustomer(getApplicationContext(), mCustomerUuid, isImported);
                                        ebtapi.deleteCustomerById(mCustomerUuid).compose(RxUtil.rxTransformer(ActivityCustomerAll.this)).subscribe(getCustomerDeleteSubscriber());
                                    }
                                }
                            };
                            deleteCustomer.start();
                            TCAgent.onEvent(getApplicationContext(), "delete_customer");
                        }
                    })
                    .setContentViewClickable(false)
                    .create()
                    .show();

        }
    }

    private Observer<CustomerCRUDRetJson> getCustomerDeleteSubscriber() {
        return new Observer<CustomerCRUDRetJson>() {
            @Override
            public void onComplete() {
            }

            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                showToast(getResources().getString(R.string.network_fail));
                backAndRefreshCustomer();
            }

            @Override
            public void onNext(CustomerCRUDRetJson customerCRUDRetJson) {

                if (customerCRUDRetJson == null) {
                    showToast(getResources().getString(R.string.network_fail));
                    backAndRefreshCustomer();
                    return;
                }
                if (customerCRUDRetJson.error != null) {
                    showToast(getResources().getString(R.string.network_fail));
                    backAndRefreshCustomer();
                    return;
                }
                if (customerCRUDRetJson.error == null) {
                    if (customerCRUDRetJson.data == null) {
                        showToast(getResources().getString(R.string.network_fail));
                        backAndRefreshCustomer();
                        return;
                    } else {
                        ToastUtil.showToast("客户删除成功");
                        backAndRefreshCustomer();
                    }
                }
            }
        };
    }

    private void backAndRefreshCustomer() {
        getWindow().getDecorView().postDelayed(new Runnable() {
            @Override
            public void run() {
//                EventBus.getDefault().post(new Customer());
//                EventBus.getDefault().post(new CustomerInteraction());
//                EventBus.getDefault().post(new CustomerEvent());
//                EventBus.getDefault().post(new GetCustomerEvent());
                EventBus.getDefault().post(new EventCustomerListRefresh());
                onBackPressed();
            }
        }, CustomerConstant.Delay.RIPPLE_DELAY);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        RecorderWrapper recorderWrapper = RecorderWrapper.getInstance();
        boolean isPlaying = false;
        try {
            isPlaying = recorderWrapper.isPlaying();
        } catch (IllegalStateException e) {
            e.printStackTrace();
            recorderWrapper = null;
        }
        if (isPlaying) {
            recorderWrapper.releasePlayer();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EventFloatingActionButton event) {
        if (event == null) {
            return;
        }
        if (event.show) {
            showFAB();
        } else {
            hideFAB();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EventCustomerListRefresh event) {
        if (event != null) {
            if (mCustomerUuid != null) {
                ebtapi.getCustomerDetail(mCustomerUuid).compose(RxUtil.rxTransformer(this)).subscribe(getCustomerDetailSubscriber());
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EventCustomerFloatingButtonAction event) {
        if (event != null) {
            switch (event.index) {
                case EventCustomerFloatingButtonAction.Attachment://附件
                    pressAttachment();
                    break;
                case EventCustomerFloatingButtonAction.Note://笔记
                    pressNote();
                    break;
                case EventCustomerFloatingButtonAction.Proposal://计划书
                    pressProposal();
                    break;
                case EventCustomerFloatingButtonAction.Policy://保单
                    pressInsurance();
                    break;
            }
        }
    }


    int mFABDistance = 0;

    public void showFAB() {
        getFABTranslationDistance();
        mFloatingActionButton.animate().translationY(0).setInterpolator(new DecelerateInterpolator(2)).start();
    }

    public void hideFAB() {
        getFABTranslationDistance();
        mFloatingActionButton.animate().translationY(mFABDistance).setInterpolator(new AccelerateInterpolator(2)).start();
    }

    private void getFABTranslationDistance() {
        if (mFABDistance == 0) {
            int height = ((WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getHeight();
            int[] location = new int[2];
            mFloatingActionButton.getLocationOnScreen(location);
            mFABDistance = height - location[0];
        }
    }

    private void delayFinish() {
        getWindow().getDecorView().postDelayed(new Runnable() {
            @Override
            public void run() {
                onBackPressed();
            }
        }, 1000);
    }

}
